﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization;
using System.IO;
using System.Text;
using System.Net;
using System.Web.Security;
using LitJson;
using Newtonsoft.Json.Linq;
namespace JumbotPay.API.YunGouOS.WxPay
{
    public class JsApiPay
    {
        /// <summary>
        /// 保存页面对象，因为要在类的方法中使用Page的Request对象
        /// </summary>
        private Page page {get;set;}

        /// <summary>
        /// openid用于调用统一下单接口
        /// </summary>
        public string openid { get; set; }

        /// <summary>
        /// access_token用于获取收货地址js函数入口参数
        /// </summary>
        public string access_token { get; set; }

        /// <summary>
        /// 商品金额，用于统一下单
        /// </summary>
        public int total_fee { get; set; }


        public string account_wxpay { get; set; }


        /// <summary>
        /// 统一下单接口返回结果
        /// </summary>
        public WxPayData unifiedOrderResult { get; set; } 

        public JsApiPay(Page page)
        {
            this.page = page;
        }


        /**
        * 
        * 网页授权获取用户基本信息的全部过程
        * 详情请参看网页授权获取用户基本信息：http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
        * 第一步：利用url跳转获取code
        * 第二步：利用code去获取openid和access_token
        * 
        */
        public void GetOpenidAndAccessToken(string redirect_url,string order_id)
        {
            string _posturl = "https://api.pay.yungouos.com/api/wxlogin/getOauthUrl";
            string _postData = "";
            string _json = "";
            _postData = "url=" + System.Web.HttpUtility.UrlEncode(redirect_url);
            _postData += "&params=" + System.Web.HttpUtility.UrlEncode(order_id);
            _json = JumbotPay.Utils.HttpHelper.Post_Http(_posturl, _postData, Encoding.UTF8);
            JObject jo = JObject.Parse(_json);
            string url = jo["data"].ToString();
            JumbotPay.Utils.Logs.Debug("wxpayM_get_opeid", url);
            try
            {

                //触发微信返回code码         
                page.Response.Redirect(url);//Redirect函数会抛出ThreadAbortException异常，不用处理这个异常
            }
            catch (System.Threading.ThreadAbortException ex)
            {
            }
        }

        public void GetOpenidAndParamsFromCode(string account_wxpay, string code, ref string order_id)
        {
            try
            {
                //构造获取openid的url
                WxPayData data = new WxPayData();
                data.SetValue("code", code);
                string _url = "https://api.pay.yungouos.com/api/wxlogin/getBaseOauthInfo?" + data.ToUrl();

                //请求url以获取数据
                string result = JumbotPay.Utils.HttpHelper.Get_Http(_url, 8000, Encoding.UTF8);
                JObject jo = JObject.Parse(result);
                string _code = jo["code"].ToString();
                if (_code == "0")
                {
                    openid = jo["data"]["openId"].ToString();
                    order_id = jo["data"]["params"]["params"].ToString();
                    JumbotPay.Utils.Logs.Info("GetOpenidAndParamsFromCode", "openid:" + openid, false);
                    JumbotPay.Utils.Logs.Info("GetOpenidAndParamsFromCode", "order_id:" + order_id, false);
                }
                else
                {
                    JumbotPay.Utils.Logs.Error("GetOpenidAndAccessTokenFromCode", result, false);
                }
            }
            catch (Exception ex)
            {
                JumbotPay.Utils.Logs.Error("GetOpenidAndAccessTokenFromCode", ex.ToString(), false);
                throw new WxPayException(ex.ToString());
            }
        }

        /**
         * 调用统一下单，获得下单结果
         * @return 统一下单结果
         * @失败时抛异常WxPayException
         */
        public string GetUnifiedOrderResult(WxPayData inputObj, string account_wxpay)
        {

            string result = new WxPayApi().UnifiedOrder_JsApiPay(inputObj, account_wxpay, 6);
            return result;
        }


    
        public string GetJsApiParameters(string json)
        {
            Newtonsoft.Json.Linq.JObject jo = Newtonsoft.Json.Linq.JObject.Parse(json);
            WxPayData jsApiParam = new WxPayData();
            jsApiParam.SetValue("appId", jo["appId"].ToString());
            jsApiParam.SetValue("timeStamp", jo["timeStamp"].ToString());
            jsApiParam.SetValue("nonceStr", jo["nonceStr"].ToString());
            jsApiParam.SetValue("package", jo["package"].ToString());
            jsApiParam.SetValue("signType", jo["signType"].ToString());
            jsApiParam.SetValue("paySign", jo["paySign"].ToString());

            string parameters = jsApiParam.ToJson();
            return parameters;
        }

        public string GetEditAddressParameters(string account_wxpay)
	    {
            string parameter = "";
            try
            {
                string host = page.Request.Url.Host;
                string path = page.Request.Path;
                string queryString = page.Request.Url.Query;
                //这个地方要注意，参与签名的是网页授权获取用户信息时微信后台回传的完整url
                string url = "http://" + host + path + queryString;

                //构造需要用SHA1算法加密的数据
                WxPayData signData = new WxPayData();
                WxPayConfig conf = new WxPayConfig(account_wxpay);
                signData.SetValue("appid", conf.APPID);
                signData.SetValue("url", url);
                signData.SetValue("timestamp", new WxPayApi().GenerateTimeStamp());
                signData.SetValue("noncestr", new WxPayApi().GenerateNonceStr());
                signData.SetValue("accesstoken",access_token);
                string param = signData.ToUrl();

                Log.Debug(this.GetType().ToString(), "SHA1 encrypt param : " + param);
                //SHA1加密
                string addrSign = FormsAuthentication.HashPasswordForStoringInConfigFile(param, "SHA1");
                Log.Debug(this.GetType().ToString(), "SHA1 encrypt result : " + addrSign);

                //获取收货地址js函数入口参数
                WxPayData afterData = new WxPayData();
                afterData.SetValue("appId", conf.APPID);
                afterData.SetValue("scope","jsapi_address");
                afterData.SetValue("signType","sha1");
                afterData.SetValue("addrSign",addrSign);
                afterData.SetValue("timeStamp",signData.GetValue("timestamp"));
                afterData.SetValue("nonceStr",signData.GetValue("noncestr"));

                //转为json格式
                parameter = afterData.ToJson();
                Log.Debug(this.GetType().ToString(), "Get EditAddressParam : " + parameter);
            }
            catch (Exception ex)
            {
                Log.Error(this.GetType().ToString(), ex.ToString());
                throw new WxPayException(ex.ToString());
            }

            return parameter;
	    }
    }
}